<?php
namespace Components\User\Sha;

class Service {
  public function create($data) {
    $findFirstUser = Model::findFirst(['account = "' . $data['account'] . '"']);
    if($findFirstUser) { return ['code'=>-1,'msg'=>'账号已存在']; }

    $findFirstUserCellphone = Model::findFirst(['cellphone = "' . $data['cellphone'] . '"']);
    if($findFirstUserCellphone) { return ['code'=>-1,'msg'=>'手机号已存在']; }

    $model = new Model($data);
    if(!$model -> create()) {
      $messages = $model -> getMessages();
      return ['code' => -1, 'msg' => $messages[0] -> getMessage()];
    }

    return ['code' => 0, 'model'=>$model, 'msg' => '创建成功'];
  }

  public function findFirst($parameters = []) {
    $model = Model::findFirst($parameters);
    if(!$model) {
      return ['code' => -1, 'msg' => '数据不存在或已删除'];
    }

    return ['code'=>0, 'model'=>$model];
  }

  public function findFirstByIdUseBackendAndUnsetPassword($id) {
    $model = \Phalcon\Di::getDefault() -> getShared('cacheBackend') -> get('user/'.$id);
    if(!$model) {
      $resUser = $this -> findFirst(['conditions'=>'id = '.$id]);
      if($resUser['code'] != 0) { return $resUser; }

      $model = $resUser['model'] -> toArray();
      unset($model['login_password']);
      unset($model['safe_password']);

      \Phalcon\Di::getDefault() -> getShared('cacheBackend') -> save('user/'.$id, $model);
    }

    return ['code'=>0,'model'=>$model];
  }
}
